package com.dg11185.nearshop.activity.user.info;

import android.content.Context;

import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.utils.string.StringUtils;
import com.dg11185.nearshop.net.request.GeneralRequest;
import com.dg11185.nearshop.net.request.GetUserDetailRequest;
import com.dg11185.nearshop.net.response.GetUserDetailResponse;
import com.dg11185.nearshop.net.response.NetStatus;

/**
 * 
 * @author：Daibo
 * @time：2014-9-12 下午2:51:24
 */
public class UserInfoModel implements IUserInfoModel {

    private Context mContext = null;

    private GetUserDetailResponse userDetail = null;

    private GetUserDetailRequest detailRequest = null;

    private GeneralRequest generalRequest = null;

    private UserInfoPresenter presenter = null;

    public UserInfoModel(UserInfoPresenter presenter, Context context, String userId) {
        this.presenter = presenter;
        this.mContext = context;
        detailRequest = new GetUserDetailRequest(userId);
        generalRequest = new GeneralRequest(GeneralRequest.MODIFY_DETAIL).add("userId", userId);
    }

    @Override
    public void getUserInfo() {
        detailRequest.setActionListener(new GetUserDetailRequest.ActionListener<GetUserDetailResponse>() {

            @Override
            public void onSuccess(GetUserDetailResponse response) {
                if (NetStatus.SUCCESS == response.status) {
                    userDetail = response;
                    presenter.onGetInfoSuccess(response);
                } else {
                    onFailure(-1);
                }
            }

            @Override
            public void onFailure(int resultCode) {
                presenter.onGetInfoFailure(resultCode);
            }
        });
        NetClient.httpGet(mContext, detailRequest);
    }

    @Override
    public void submitBrithDay(String birth) {
        if (!StringUtils.isBlank(birth) && userDetail != null) {
            userDetail.birthday = birth;
            submitModify();
        }
    }

    @Override
    public void submitGender(String gender) {
        if (!StringUtils.isBlank(gender) && userDetail != null) {
            userDetail.sex = gender;
            submitModify();
        }
    }

    private void submitModify() {

        generalRequest.add("birthday", userDetail.birthday).add("sex", userDetail.sex).encryption();

        generalRequest.setActionListener(new GeneralRequest.ActionListener<NetStatus>() {

            @Override
            public void onSuccess(NetStatus result) {
                if (NetStatus.SUCCESS == result) {
                    presenter.onSubmitSuccess();
                }
            }

            @Override
            public void onFailure(int resultCode) {
                presenter.onSubmitFailure(resultCode);
            }
        });
        NetClient.httpPost(mContext, generalRequest);
    }

}
